<template>
  <div class="file-upload-container">
    <div
      class="ant-upload ant-upload-drag"
      :class="{ 'ant-upload-disabled': disabled }"
      @click="triggerFileInput"
      @dragover.prevent="handleDragOver"
      @drop.prevent="handleDrop"
    >
      <input
        type="file"
        ref="fileInput"
        :accept="acceptTypes"
        :disabled="disabled"
        @change="handleFileChange"
        style="display: none"
      />
      <p class="ant-upload-drag-icon">
        <a-icon type="inbox" />
      </p>
      <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
      <p class="ant-upload-hint">
        支持{{ acceptTypes || '任意' }}格式，单文件不超过{{ maxSize }}MB
      </p>
      <a-button :loading="uploading">
        <a-icon type="upload" /> {{ uploading ? '处理中...' : '选择文件' }}
      </a-button>
    </div>

    <!-- 文件列表展示 -->
    <div class="file-list" v-if="internalFileList.length > 0">
      <div class="file-item" v-for="file in internalFileList" :key="file.uid">
        <span class="file-name">{{ file.name }}</span>
        <a-icon type="close" @click="handleRemove(file)" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FileUpload',
  props: {
    fileList: {
      type: Array,
      default: () => [],
      validator: (value) => {
        return value.every(file => file.uid && file.name)
      }
    },
    acceptTypes: {
      type: String,
      default: '' // 例如: '.jpg,.png,.pdf'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    maxSize: {
      type: Number,
      default: 10 // MB
    }
  },
  data() {
    return {
      uploading: false,
      internalFileList: [...this.fileList]
    }
  },
  watch: {
    fileList(newVal) {
      this.internalFileList = [...newVal]
    }
  },
  methods: {
    // 触发文件选择
    triggerFileInput() {
      if (!this.disabled) {
        this.$refs.fileInput.click()
      }
    },

    // 处理文件选择
    handleFileChange(event) {
      const files = event.target.files
      if (files.length > 0) {
        this.processFile(files[0])
      }
      event.target.value = '' // 重置input，允许重复选择同一文件
    },

    // 处理拖放
    handleDragOver() {
      // 可以添加拖拽时的视觉效果
    },

    handleDrop(event) {
      if (this.disabled) return
      
      const files = event.dataTransfer.files
      if (files.length > 0) {
        this.processFile(files[0])
      }
    },

    // 处理文件
    processFile(file) {
      // 文件类型校验
      if (this.acceptTypes) {
        const acceptedTypes = this.acceptTypes.split(',').map(t => t.trim())
        const fileExtension = file.name.split('.').pop().toLowerCase()
        const isValidType = acceptedTypes.some(type => 
          type.startsWith('.') 
            ? `.${fileExtension}` === type.toLowerCase()
            : file.type.includes(type.replace('.', ''))
        )
        
        if (!isValidType) {
          this.$message.error(`仅支持 ${this.acceptTypes} 格式的文件!`)
          return
        }
      }
      
      // 文件大小校验
      const isLtMaxSize = file.size / 1024 / 1024 < this.maxSize
      if (!isLtMaxSize) {
        this.$message.error(`文件大小不能超过 ${this.maxSize}MB!`)
        return
      }

      this.uploading = true
      const reader = new FileReader()

      reader.onload = (event) => {
        const fileInfo = {
          uid: this.generateUid(),
          name: file.name,
          size: file.size,
          type: file.type,
          lastModified: file.lastModified,
          base64Content: event.target.result,
          originFileObj: file
        }
        
        this.internalFileList = [fileInfo]
        this.$emit('uploadCallBack', [fileInfo])
        this.uploading = false
      }

      reader.onerror = () => {
        this.$message.error('文件读取失败')
        this.uploading = false
      }

      reader.readAsDataURL(file)
    },

    // 生成唯一ID
    generateUid() {
      return Date.now().toString(36) + Math.random().toString(36).substr(2)
    },

    // 移除文件
    handleRemove(file) {
      const newFileList = this.internalFileList.filter(f => f.uid !== file.uid)
      this.internalFileList = newFileList
      this.$emit('uploadCallBack', newFileList)
    },

    // 清空文件
    clearFiles() {
      this.internalFileList = []
      this.$emit('uploadCallBack', [])
    }
  }
}
</script>

<style scoped>
.file-upload-container {
  width: 100%;
}

.ant-upload-drag {
  padding: 16px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background: #fafafa;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.ant-upload-drag:hover {
  border-color: #1890ff;
}

.ant-upload-disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.ant-upload-disabled:hover {
  border-color: #d9d9d9;
}

.file-list {
  margin-top: 16px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-top: 8px;
}

.file-item i {
  cursor: pointer;
  color: #ff4d4f;
}

.file-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>